const express = require('express');
const { auth } = require('../middleware/auth');
const validate = require('../middleware/validate');
const searchHistoryValidation = require('../validators/searchHistory.validator');
const searchHistoryController = require('../controllers/searchHistory.controller');
const { searchHistoryService } = require('../services');
const logger = require('../utils/logger');

const router = express.Router();

// 获取用户搜索历史
router.get('/', auth(), validate(searchHistoryValidation.getUserSearchHistory), searchHistoryController.getUserSearchHistory);

// 清除用户搜索历史
router.delete('/', auth(), validate(searchHistoryValidation.clearSearchHistory), searchHistoryController.clearSearchHistory);

// 测试接口 - 直接添加一条搜索历史
router.post('/test', auth(), async (req, res) => {
  try {
    logger.info('接收到测试搜索历史请求');
    // 记录用户信息
    logger.info(`用户信息: ${JSON.stringify({
      hasUser: !!req.user,
      userId: req.user ? req.user.id || req.user._id : 'unknown',
      userProps: req.user ? Object.keys(req.user) : []
    })}`);
    
    if (!req.user) {
      return res.status(401).json({
        error: 1,
        body: null,
        message: '用户未登录'
      });
    }
    
    const userId = req.user.id || req.user._id;
    if (!userId) {
      return res.status(400).json({
        error: 1,
        body: null,
        message: '用户ID无效'
      });
    }
    
    const keyword = req.body.keyword || '测试关键词';
    const type = req.body.type || 'food';
    
    const historyData = {
      userId,
      keyword,
      type
    };
    
    logger.info(`准备创建测试搜索历史: ${JSON.stringify(historyData)}`);
    const result = await searchHistoryService.createSearchHistory(historyData);
    
    res.status(201).json({
      error: 0,
      body: {
        _id: result._id,
        userId: result.userId,
        keyword: result.keyword,
        type: result.type,
        createdAt: result.createdAt
      },
      message: '测试搜索历史创建成功'
    });
  } catch (error) {
    logger.error(`测试搜索历史创建失败: ${error.message}`);
    logger.error(`错误堆栈: ${error.stack}`);
    
    res.status(500).json({
      error: 1,
      body: null,
      message: error.message || '测试搜索历史创建失败'
    });
  }
});

module.exports = router; 